package com.example.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.core.domain.Result;
import com.example.order.entity.Order;
import com.example.order.feign.ProductFeignClient;
import com.example.order.mapper.OrderMapper;
import com.example.order.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final ProductFeignClient productFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(Long userId, Long productId, Integer quantity) {
        // 调用商品服务扣减库存
        Result<Boolean> result = productFeignClient.decreaseStock(productId, quantity);
        if (!result.getData()) {
            throw new RuntimeException("库存不足");
        }

        // 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setProductId(productId);
        order.setQuantity(quantity);
        // 这里简化处理，实际应该从商品服务获取商品信息
        order.setProductName("测试商品");
        order.setProductPrice(new BigDecimal("100.00"));
        order.setTotalAmount(order.getProductPrice().multiply(new BigDecimal(quantity)));
        order.setStatus(0); // 待支付
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        save(order);
        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Long orderId) {
        Order order = getById(orderId);
        if (order == null || order.getStatus() != 0) {
            return false;
        }

        order.setStatus(1); // 已支付
        return updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long orderId) {
        Order order = getById(orderId);
        if (order == null || order.getStatus() != 0) {
            return false;
        }

        order.setStatus(2); // 已取消
        return updateById(order);
    }
} 